<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Knowledge Graph with Cytoscape.js</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        #cy {
            width: 100%;
            height: 100vh;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="cy"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.min.js"></script>
    <script>
    // 定义图数据
    const graphData = {
      nodes: [
        { data: { id: "A", name: "Node A" } },
        { data: { id: "B", name: "Node B" } },
        { data: { id: "C", name: "Node C" } },
        { data: { id: "D", name: "Node D" } }
      ],
      edges: [
        { data: { id: "AB", source: "A", target: "B" } },
        { data: { id: "BC", source: "B", target: "C" } },
        { data: { id: "CD", source: "C", target: "D" } },
        { data: { id: "DA", source: "D", target: "A" } }
      ]
    };

    // 初始化 Cytoscape
    const cy = cytoscape({
      container: document.getElementById('cy'),
      elements: {
        nodes: graphData.nodes,
        edges: graphData.edges
      },
      style: [
        {
          selector: 'node',
          style: {
            'background-color': '#69b3a2',
            'label': 'data(name)',
            'color': '#333',
            'font-size': '12px',
            'text-valign': 'center',
            'text-halign': 'right',
            'text-margin-x': '10px',
            'width': '20px',
            'height': '20px',
            'border-width': '2px',
            'border-color': '#fff'
          }
        },
        {
          selector: 'edge',
          style: {
            'width': 2,
            'line-color': '#999',
            'curve-style': 'bezier',
            'opacity': 0.6
          }
        }
      ],
      layout: {
        name: 'cose',
        idealEdgeLength: 100,
        nodeOverlap: 20,
        refresh: 20,
        fit: true,
        padding: 30,
        randomize: false,
        componentSpacing: 100,
        nodeRepulsion: 400000,
        edgeElasticity: 100,
        nestingFactor: 5,
        gravity: 80,
        numIter: 1000,
        initialTemp: 200,
        coolingFactor: 0.95,
        minTemp: 1.0
      }
    });

    // 添加节点拖拽功能
    cy.on('mousedown', 'node', function(e){
      const node = e.target;
      node.unlock();
    });

    cy.on('mouseup', 'node', function(e){
      const node = e.target;
      node.lock();
    });

    // 双击画布添加新节点
    cy.on('dblclick', function(e){
      if(e.target === cy){
        const position = e.position;
        const id = 'node-' + Math.floor(Math.random() * 1000);
        cy.add({
          group: 'nodes',
          data: { id: id, name: 'New Node' },
          position: position
        });
      }
    });
    </script>
</body>
</html>